<template>
	<div class="place_order_entity">
		<title-bar :title="'生成订单'" />
		<bottom-goods-info
			style="margin-bottom: 20px;margin-top: 46px;"
			v-if="products"
			:goods="products"
			:coupons="coupons"
			:giveGift="giveGift"
			@payPriceChange="payPrice = $event"
			@parCartChange="parCartChange"
			@discountAmount="discountAmount = $event"
			@fanhuiDis="fanhuiDis=$event"
			@couponChange="onCouponChange" />
		<top-user-info v-if="products" :order="order" @userInfoChange="onUserInfoChange($event)" />
		<van-submit-bar
			:price="payPrice * 100"
			label="总计："
			buttonText="提交订单"
			:loading="isSubmit"
			:disabled="isDisabled"
			@submit="onSubmit"
		/>
	</div>
</template>

<script>
	import topUserInfo from "../top-user-info";
	import bottomGoodsInfo from './bottom-goods-info';
	import TitleBar from '@/vue/components/title-bar/';
	import { SubmitBar } from 'vant';
	import { PRE_ORDER, CREATE_ORDER } from '@/api/order';
	import { mobile } from '@/assets/js/regexp.js';
	import wxConfig from '@/vue/mixin/wx-config';
	

	export default {
	  mixins: [wxConfig],
	  data() {
	    return {
	      isSubmit: false,
				isDisabled: false,
	      order: null,
	      products: null,
	      coupons: null,
	      selCouponId: null,
				payPrice: 0,
				discountAmount:0,
				fanhuiDis:'',
				sessionOrder:'',
				sessionCartItems:"",
				giveGift:'',//保存赠品的信息
	    }
	  },
			watch:{
				//改变优惠券金额时，再次调用商品加减将优惠金额传过去
			fanhuiDis(newDis){
				this.fanhuiDis = newDis;
				this.isYouHui(this.fanhuiDis,1);	
			},
			sessionCartItems(){
				// console.log('没有监听到改变')
				this.isYouHui(0);
			},
			coupons(ele){
				this.coupons = ele;
			}
		},
	  created() {
			let youhuiMon = this.$util.getSessionStorage('youhuiMon')
			this.isYouHui(youhuiMon);
	  },

	  methods: {
			//back 参数用来区分是否是点击优惠券返回
			isYouHui(value,back=0){
					 let productsId = [];
						const order = this.$util.getSessionStorage("order");

						this.$reqPost(PRE_ORDER, {
							memberId: this.user.id,
							products: order.cartItems,
							discountAmount:value
						}, {
							dataType: "json"
						}).then(res => {
							let products = res.data.data;
							this.giveGift = res.data.gift;
							if (back == 0) {
								console.log('优惠券内容改变了')
								this.coupons = res.data.coupons || [];
							}
							if (res.data.overtime) {
								this.$dialog.alert({
									message: '部分商品已经停售，无法下单'
								});
							}

							const assistMode = this.isAssistMode(); //代客下单模式
							const shop = this.getShop();
							this.order = {
								mid: this.user.id,
								realname: this.user.realname,
								nickname: this.user.nickname,
								mobile: this.user.mobile,
								sname: assistMode ? '' : (this.user.realname || this.user.nickname),
								saddress: this.user.address,
								shopName: shop.realname,
								shopMobile: shop.mobile,
								shopXiaoqu: shop.tXiaoqu,
								shopAddress: shop.tProvince + shop.tCity + shop.tArea + shop.tXiaoqu + shop.tShopname,
							};

							this.products = products;
							this.products.forEach(goods => {
								for (let i = 0; i < order.cartItems.length; ++i) {
									let cartItem = order.cartItems[i];
									if (cartItem.productId === goods.id && !cartItem.findGoods) {
										goods.total = cartItem.total || 1;
										goods.cartId = cartItem.cartId;

										if (cartItem.skuId) {
											goods.skuId = cartItem.skuId;
											goods.optionname = cartItem.skuTitle;
											goods.marketprice = cartItem.marketprice;
											goods.vipprice = cartItem.vipprice;
										}
										cartItem.findGoods = true; //用于同一商品多规格时的判断
										break;
									}
								}
							});
						});
			},
			parCartChange(ele){
				//购物车数量改变
				this.sessionCartItems = ele;
			},
	    onSubmit() {
	      if (!this.order.sname || !this.order.mobile || !mobile(this.order.mobile)) {
	        this.$toast('请正确填写收件人姓名和电话');
	        return;
	      }

	      const check = this.checkShop();

	      if (check !== 1) {
	        this.$dialog.alert({
	          message: '当前团长已经关闭或者打烊中，请选择其他团长进行下单'
	        }).then(() => {
	          this.$router.push({
	            name: 'home'
	          });
	        });
	        return;
	      }

	      const confirm = this.showPickPromote();
	      if (confirm) {
	        this.$dialog.confirm({
	          title: '确认下单',
	          message: '请确认提货地址：' + this.order.shopXiaoqu
	        }).then(() => {
	          this.submitOrder();
	        }).catch(() => {});
	      } else {
	        this.submitOrder();
	      }
	    },

	    submitOrder() {
	      this.isSubmit = true;
	      let products = this.products.map(item => {
	        return {
	          id: item.cartId,
	          productId: item.id,
	          total: item.total,
	          mid: this.user.id,
	          teamid: this.user.upshopTid,
	          openid: this.user.openid,
						skuId: item.skuId
	        }
	      });

	      let params = {
	        memberId: this.user.id,
	        products: products,
	        sname: this.order.sname + (this.isAssistMode() ? '(代客下单)' : ''),
	        mobile: this.order.mobile,
	        houseNo: "",
					couponId: this.selCouponId,
					giftId:this.giveGift.id,
					discountAmount:this.discountAmount
	      };
				//对赠品信息为0进行处理
				if (!this.giveGift.total && this.giveGift !="") {
						params.giftId = '';
						//提示赠品已经卖完
						this.$dialog.confirm({
	            title: '提示',
  						message: '赠品已送完,是否继续提交订单~'
	          }).then(() => {
								this.$reqPost(CREATE_ORDER, params, {
									dataType: "json"
								}).
								then(res => {
									if (res.data.success) {
										//减少购物车数量
										products.forEach(product => {
											if (product.id) {
												this.changeCartNum(-product.total);
											}
										});
										this.$util.setLocalStorage('lastShopTid', this.user.upshopTid);
										let vm = this;
										this.isWxApp().then(app => {
											if (app) {
												vm.$router.replace({
													name: "payment",
													params: {
														payId: res.data.data
													}
												})
											} else {
												location.replace(vm.getUri() + "order/payment/" + res.data.data);
											}
										});
									} else {
										this.$dialog.alert({
											message: res.data.msg
										});
										this.isSubmit = false;
									}
								}).catch(() => {
									this.isSubmit = false;
								});
						}).catch(() => {
							this.isSubmit = false;
						});
						return;
				}
	      this.$reqPost(CREATE_ORDER, params, {
	        dataType: "json"
				})
				.then(res => {
	        if (res.data.success) {
	          //减少购物车数量
	          products.forEach(product => {
	            if (product.id) {
	              this.changeCartNum(-product.total);
	            }
	          });
	          this.$util.setLocalStorage('lastShopTid', this.user.upshopTid);
	          let vm = this;
	          this.isWxApp().then(app => {
	            if (app) {
	              vm.$router.replace({
	                name: "payment",
	                params: {
	                  payId: res.data.data
	                }
	              })
	            } else {
	              location.replace(vm.getUri() + "order/payment/" + res.data.data);
	            }
	          });
	        } else {
	          this.$dialog.alert({
	            message: res.data.msg
	          });
	          this.isSubmit = false;
	        }
	      }).catch(() => {
	        this.isSubmit = false;
	      });
	    },

	    onUserInfoChange(info) {
	      this.order.sname = info.name.trim();
	      this.order.mobile = info.mobile.trim();

	      if (!this.user.mobile) {
	        this.user.mobile = this.order.mobile;
	      }
	    },
	    onCouponChange(index) {
	      if (index > -1) {
	        this.selCouponId = this.coupons[index].id;
	      } else {
	        this.selCouponId = null;
	      }
	    }
	  },

	  components: {
	    [SubmitBar.name]: SubmitBar,
	    [topUserInfo.name]: topUserInfo,
	    [bottomGoodsInfo.name]: bottomGoodsInfo,
			[TitleBar.name]: TitleBar
	  }
	}
</script>

<style lang="scss" scoped>
	.place_order_entity{
		padding-bottom: 70px;
	}
</style>
